package com.hexorld.main;

import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;

import com.hexorld.core.Constants;
import com.hexorld.core.Position;
import com.hexorld.core.UpdateFlag;
import com.hexorld.layer.ActionLayer;
import com.hexorld.layer.BgLayer;
import com.hexorld.layer.FrontLayer;
import com.hexorld.layer.Layer;
import com.hexorld.layer.LayerManager;
import com.hexorld.sprite.Evoe;
import com.hexorld.sprite.Food;
import com.hexorld.sprite.SpriteManager;

public class GameModel {
	private LayerManager mLayerManager = null;
	private SpriteManager mSpriteManager = null;
	private Context mContext;
	public GameModel(Context context){
		mContext = context;
		mLayerManager = new LayerManager();
		mSpriteManager = new SpriteManager(mLayerManager);
		initLayers();
		
		test(); //FOR TEST ONLY
	}
	
	//FOR TEST ONLY

	void test(){
		Evoe player = new Evoe(mContext, new Position(160, 160));
		Food food1 = new Food(mContext, 60, 60);
		food1.spawn();
		Food food2 = new Food(mContext, 30, 30);
		food2.spawn();
		if(mSpriteManager != null)
		{
			mSpriteManager.addSprite(player);
			player.setCollisionManger(mSpriteManager);
			mSpriteManager.addSprite(food1);
			food1.setCollisionManger(mSpriteManager);
			mSpriteManager.addSprite(food2);		
			food2.setCollisionManger(mSpriteManager);
		}
		if(mLayerManager != null)
		{
			mLayerManager.getLayerAt(1).add(player);
			mLayerManager.getLayerAt(1).add(food1);
			mLayerManager.getLayerAt(1).add(food2);
		}
		
		
	}
	
	private void initLayers(){
		//Background layer
		Layer layer = new BgLayer(mContext, Constants.GAME_BOARD_WIDTH, Constants.GAME_BOARD_HEIGHT, 0);
		mLayerManager.addLayer(layer.Z, layer);
		
		//Action layer for dynamic object
		layer = new ActionLayer(mContext, Constants.GAME_BOARD_WIDTH, Constants.GAME_BOARD_HEIGHT, 1);
		mLayerManager.addLayer(layer.Z, layer);
		
		//Front layer for something should display before Action layer
		layer = new FrontLayer(mContext, Constants.GAME_BOARD_WIDTH, Constants.GAME_BOARD_HEIGHT, 2);
		mLayerManager.addLayer(layer.Z, layer);
	}
	
	public void draw(Canvas canvas) {
		if(canvas == null || mLayerManager == null)
			return;
		mLayerManager.drawAll(canvas);
	}
	
	public void update(UpdateFlag updateFlag) {
		if(mSpriteManager != null)
			mSpriteManager.updateAll(updateFlag);
	}
	
	public boolean onTouchEvent(MotionEvent event){
		if(mLayerManager != null)
			mLayerManager.onTouchEvent(event);
		return true;
	}

}
